package cn.tedu.rtc.component.websocket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

/**
 * 第一步：ws链接认证
 */
@Slf4j
@Component
public class AuthPrincipalHandler extends DefaultHandshakeHandler {

    @Override
    protected boolean isValidOrigin(ServerHttpRequest request) {
        log.info("开始认证ws链接");
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            String token = servletRequest.getParameter("x-auth-token");
            String workspaceId = servletRequest.getParameter("project-id");
            String userType = servletRequest.getParameter("user-type");
            String userId = servletRequest.getParameter("user-id");
            log.info(String.format("token:%s, workspaceId:%s, userType:%s, userId:%s", token, workspaceId, userType, userId));
        }
        return true;
    }

    /**
     * The principal's name: {workspaceId}/{userType}/{userId}
     * @param request
     * @param wsHandler
     * @param attributes
     * @return
     */
    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        log.info("开始确定用户信息");

        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            String token = servletRequest.getParameter("x-auth-token");
            String workspaceId = servletRequest.getParameter("project-id");
            String userType = servletRequest.getParameter("user-type");
            String userId = servletRequest.getParameter("user-id");

            return () -> workspaceId + "/" + userType + "/" + userId;
        }

        return () -> null;
    }
}